package com.example.demo.service.impl;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

public class PinyinUtil {
    private static HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    static {
        // 设置大小写格式
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        // 设置声调格式：
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    public static String first(String str) {
        char ch = str.trim().charAt(0);
        if (ch >= 'a' && ch <= 'z') {
            return (char) (ch - 'a' + 'A') + "";
        }

        if (ch >= 'A' && ch <= 'Z') {
            return ch + "";
        }

        try {
            if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]+")) {
                String[] array = PinyinHelper.toHanyuPinyinStringArray(ch, defaultFormat);
                if (array != null && array.length > 0) {
                    return array[0].charAt(0) + "";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "#";
    }

    public static void main(String[] args) {
        System.out.println(first("燊"));
    }
}
